<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>部门列表</title>
  <link rel="stylesheet" href="./static/css/layui.css" media="all">
  <link rel="stylesheet" href="./static/css/common.css">
</head>
<body>
<div>
  <table class="layui-hide" id="test" lay-filter="test"></table>
  <div class="layui-row layui-col-space2">
    <div class="layui-col-md8 layui-col-xs12" id="left" style="height:500px;"></div>
    <div class="layui-col-md4 layui-col-xs12" id="right" style="height:500px;padding: 20px"></div>
  </div>

  <script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
      <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="getCheckData"><i
              class="layui-icon layui-icon-delete"></i>删除选中项
      </button>
    </div>
  </script>

  <script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
  </script>


</div>
<script src="./static/layui.js"></script>
<script src="./static/common.js"></script>
<script src="./static/echarts.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
  layui.use(['table', 'layer', 'jquery'], function () {
    var table = layui.table
    $ = layui.$;

    table.render({
      elem: '#test'
      , url: '/StaffManagement/department/getAll'
      , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
      , defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
        title: '提示'
        , layEvent: 'LAYTABLE_TIPS'
        , icon: 'layui-icon-tips'
      }]
      , title: '用户数据表'
      , cols: [[
        {type: 'checkbox', fixed: 'left'}
        , {field: 'id', title: 'ID', width: 100, fixed: 'left', unresize: true, sort: true}
        , {field: 'departmentName', title: '部门名称', width: 150}
        , {field: 'maxSalary', title: '最高工资（单位：元）', width: 170}
        , {field: 'minSalary', title: '最低工资（单位：元）', width: 170}
        , {
          field: 'avgSalary', title: '平均工资（单位：元）', width: 170
        }
        , {
          field: 'createTime', title: '创建时间', width: 250, templet: data => {
            return new Date(data.createTime).format("yyyy-MM-dd hh:mm:ss");
          }
        }
        , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150}
      ]]
      , page: true
    });

    //头工具栏事件
    table.on('toolbar(test)', function (obj) {
      var checkStatus = table.checkStatus(obj.config.id);
      if (obj.event == 'getCheckData') {
        let user = JSON.parse(window.localStorage.getItem("user"));
        console.log(user);
        if (user.role.roleName != "管理员") {
          swal("提示", "您没有该权限", "warning");
          return;
        }
        let checkStatus = table.checkStatus(obj.config.id);
        if (checkStatus.data.length == 0) {
          swal("提示", "请选择需要删除的行", "warning");
          return;
        }
        swal({
          title: "您确定要删除吗？",
          text: "该操作将永久删除选中记录",
          icon: "warning",
          buttons: true,
          dangerMode: true,
        }).then(willDelete => {
          if (willDelete) {
            let ids = "";
            checkStatus.data.forEach(item => {
              ids += item.id + ",";
            });
            $.get("/StaffManagement/department/deleteList?ids=" + ids, "", data => {
              if (data.code == 200) {
                swal("提示", data.message, "success").then(() => {
                  table.reload('test', {
                    url: '/StaffManagement/department/getAll'
                  })
                })
              } else {
                swal("提示", data.message, "error");
              }
            })
          } else {
            swal("提示", "您取消了删除", "info");
          }
        })
      }
    });
    //监听行工具事件
    table.on('tool(test)', function (obj) {
      var data = obj.data;
      let user = JSON.parse(window.localStorage.getItem("user"));
      console.log(user);
      if (user.role.roleName != "管理员") {
        swal("提示", "您没有该权限", "warning");
        return;
      }
      if (obj.event === 'del') {
        swal({
          title: "您确定要删除吗？",
          text: "该操作将永久删除该条记录",
          icon: "warning",
          buttons: true,
          dangerMode: true,
        })
          .then((willDelete) => {
            if (willDelete) {
              $.get("/StaffManagement/department/delete?id=" + obj.data.id, "", data => {
                if (data.code == 200) {
                  swal("提示", data.message, "success").then(() => {
                    table.reload('test', {
                      url: '/StaffManagement/department/getAll'
                    })
                  });
                } else {
                  swal("提示", data.message, "error");
                }
              })
            } else {
              swal("提示", "您取消了删除", "info");
            }
          });
      } else if (obj.event === 'edit') {
        layer.open({
          type: 2,
          title: "编辑部门",
          shade: 0.2,
          maxmin: true,
          shadeClose: true,
          area: ['100%',
            '100%'],
          content: "departmentEdit.html",
          btn: ['取消'],
          anim: 4,
          success: (layero, index) => {
            let body = layer.getChildFrame('body', index);
            body.find("#curPageType").val("update");
            body.find("#id").val(obj.data.id);
            body.find("#departmentName").val(obj.data.departmentName);
            body.find("#maxSalary").val(obj.data.maxSalary);
            body.find("#minSalary").val(obj.data.minSalary);
            body.find("#avgSalary").val(obj.data.avgSalary);
            body.find("#createTime").val(new Date(obj.data.createTime).format("yyyy-MM-dd hh:mm:ss"));
            layui.form.render();
          }
        })
      }
    });


    $.get("/StaffManagement/department/getAll", "", data => {
      // 基于准备好的dom，初始化echarts实例
      var myChart1 = echarts.init(document.getElementById('left'));

      let departmentList = [];
      let maxSalaryList = [];
      let minSalaryList = [];
      let avgSalaryList = [];
      let countList = [];
      data.data.forEach(item => {
        departmentList.push(item.departmentName);
        maxSalaryList.push(item.maxSalary);
        minSalaryList.push(item.minSalary);
        avgSalaryList.push(item.avgSalary);
        countList.push({value: item.count, name: item.departmentName});
      })

      // 指定图表的配置项和数据
      var option1 = {
        title: {
          text: '部门工资信息'
        },
        tooltip: {},
        legend: {
          top: "bottom",
          data: ['最大工资', '最小工资', '平均工资']
        },
        xAxis: {
          type: "category",
          name: "部门名称",
          data: departmentList,
          axisLabel: {
            show: true,
            interval: 0
          }
        },
        yAxis: {},
        series: [{
          name: '最大工资',
          type: 'bar',
          data: maxSalaryList,
          markPoint: {
            data: [
              {
                name: "最大工资最大值",
                type: "max"
              }
            ]
          },
          markLine: {
            data: [
              {
                name: "最大工资平均值",
                type: "average"
              }
            ]
          }
        }, {
          name: '最小工资',
          type: 'bar',
          data: minSalaryList,
          markPoint: {
            data: [
              {
                name: "最小工资最小值",
                type: "min"
              }
            ]
          },
          markLine: {
            data: [
              {
                name: "最小工资平均值",
                type: "average"
              }
            ]
          }
        }, {
          name: '平均工资',
          type: 'bar',
          data: avgSalaryList,
          markPoint: {
            data: [
              {
                name: "平均工资最大值",
                type: "max"
              },
              {
                name: "平均工资最小值",
                type: "min"
              }
            ]
          },
          markLine: {
            data: [
              {
                name: "平均工资平均值",
                type: "average"
              }
            ]
          }
        }]
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart1.setOption(option1);

      var myChart2 = echarts.init(document.getElementById('right'));

      var option2 = {
        title: {
          text: '部门规格'
        },
        legend: {
          top: 'bottom'
        },
        series: [
          {
            name: '部门规格',
            type: 'pie',
            label: {
              show: true,
              position: "outside",
              formatter: "{b}\n{c}人"
            },
            radius: [0, "50%"],
            data: countList,
          }
        ]
      };

      myChart2.setOption(option2);
    })

  });


</script>
</body>
</html>